﻿using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OznerOA.Common
{
    public class HttpRestHelper
    {

        public static HttpBaseResult HttpResponse(string URL, Method method, string cookies, params string[] headers)
        {
            var client = new RestClient(URL);
            RestRequest request = null;
            request = new RestRequest(method);
            request.AddHeader("Postman-Token", "25e60354-dcf5-4648-a44d-e47b732644bb");
            request.AddHeader("Cache-Control", "no-cache");
            if (!string.IsNullOrEmpty(cookies))
                request.AddHeader("cookies", cookies);

            for (int i = 0; i < headers.Length; i += 2)
            {
                request.AddHeader(headers[i], headers[i + 1]);
            }
            IRestResponse response = client.Execute(request);

            HttpBaseResult hbr = new HttpBaseResult();
            hbr.Code = (int)response.StatusCode;
            hbr.Description = response.StatusDescription;
            hbr.Cookie = Cookies2String(response.Cookies);
            hbr.Html = response.Content;
            hbr.ContentType = response.ContentType;
            //if(response.StatusCode == System.Net.HttpStatusCode.Found) hbr.RedirectUrl = response.
            if (response.ResponseUri != null)
                hbr.ResponseUri = response.ResponseUri.ToString();
            if(hbr.Code == 0)
            {
                hbr.Description = response.ErrorMessage;
            }
            return hbr;
        }
        public static HttpBaseResult HttpGetResponse(string URL, string cookies, params string[] headers)
        {
            return HttpResponse(URL, Method.GET, cookies, headers);
        }
        public static HttpBaseResult HttpPostResponse(string URL, string cookies, params string[] headers)
        {
            return HttpResponse(URL, Method.POST, cookies, headers);
        }
        private static string Cookies2String( IList<RestResponseCookie> cookies)
        {
            string res = "";
            foreach(RestResponseCookie cookie in cookies)
            {
                res += string.Format("{0}={1};", cookie.Name, cookie.Value);
            }
            return res;
        }
    }
    
}
